<template>
  <div>
    <van-toast id="van-toast" />
    <van-dialog id="van-dialog" />

    <div class="btnm">
      <van-button size="small"  type="primary" @click="goAdd">新增</van-button>
      <van-button size="small"  type="primary" @click="goEdit">修改</van-button>
      <van-button size="small"  type="warning" @click="goDel">删除</van-button>
      <van-button size="small"  type="warning" @click="goRefresh">刷新库存</van-button>
    </div>

    <van-tree-select
      :items="items"
      :main-active-index="mainActiveIndex"
      :active-id="activeId"
      :max="max"
      @clickNav="onClickNav"
      @clickItem="onClickItem"
      >
    </van-tree-select>



    <van-dialog
      id="submitCaseDialog"
      use-slot
      :title="isEdit?'编辑'+items[mainActiveIndex].text:'添加新果品'"
      :show="dialogAddNewFormShow"
      show-cancel-button
      async-close
      @close="onClose"
    >
      <van-notify id="van-notify" />

      <view style="padding: 34rpx">

        <van-cell-group >

          <van-field
            required
            label="果品"
            :value="addnewguopin.text"
            placeholder="请输入果品名称"
            border = true
            @change = "changeVal_guopinname"
          />

          <div>
            <van-field
              label="规格名称"
              border = true
              custom-style ="width:40%;float:left"
            />
            <van-field
              label="库存数量"
              border = true
              custom-style ="width:30%;float:left"

            />
            <div
              border = true
              custom-style ="width:30%;padding:0;float:left"
              use-button-slot
              >
              <van-button  slot="button" size="mini" type="primary" @click="addguige">增加规格</van-button>
            </div>

          </div>

          <div  class="lidiv" v-for="(item,k) in addnewguige" :key="k">

          <van-field
            :data-iid = "k"
            :value="item.text"
            placeholder="输入规格名"
            @change = "changeVal_guige_name"
            border
            custom-style ="width:38%;float:left;margin-right:1%"

          />
          <van-field
            :data-iid = "k"
            :value="item.stock"
            placeholder="不限量"
            @change = "changeVal_guige_kuncun"
            border
            type="number"
            custom-style ="width:28%;float:left"

          />
            <van-button  icon="cross" size="mini" type="danger" @click="delguige(item.id)"></van-button>

            <van-switch  :data-iid = "k" :checked="item.show" size="19px"
                        @change = "changeVal_guige_show"

            />

          </div>





        </van-cell-group>
        <div style=" clear: both"></div>
      </view>

    </van-dialog>


  </div>
</template>

<script>
  import Dialog from '../../../static/vant/dialog/dialog';
  import Toast from  '../../../static/vant/toast/toast';
  import Notify from '../../../static/vant/notify/notify';

  import {categoryAdd,categoryDel,categoryEdit,categoryList} from '../../api/basisMG'

  export default {
    data () {
      return {
        isEdit:false,
        addnewguige:[{
          text:"",
          id:1,
          stock:"",
          show:true
        }
        ],
        addnewguopin:{
          text:"",
          id:"",
        },
        dialogAddNewFormShow:false,
        mainActiveIndex: 0,
        activeId: null,
        max: 2,
         items:[
        //   {
        //     // 导航名称
        //     text: '金芒果',
        //     // 禁用选项
        //     show: false,
        //     // 该导航下所有的可选项
        //     children: [
        //       {
        //         kucun:444,
        //
        //         // 名称
        //         text: '大果',
        //         // id，作为匹配选中状态的标识
        //         id: 1,
        //         // 禁用选项
        //       },
        //       {
        //         kucun:43344,
        //
        //         text: '中果',
        //         id: 2
        //       }
        //     ]
        //   },
        //   {
        //     // 导航名称
        //     text: '金2芒果',
        //     // 禁用选项
        //     show: false,
        //     dot:"1111",
        //     // 该导航下所有的可选项
        //     children: [
        //       {
        //         dot:"122111",
        //
        //         // 名称
        //         text: '大11果',
        //         // id，作为匹配选中状态的标识
        //         id: 32,
        //         // 禁用选项
        //         show: true
        //       },
        //       {
        //         text: '中222果',
        //         id: 21
        //       }
        //     ]
        //   }
        ]
      }
    },



    mounted() {
this.getList()
    },
    methods: {

      delguige(id){
        let a =  this.addnewguige.filter((o,i)=>{
          if(o.id!=id){
            return o
          }
        })

        this.addnewguige = a
      },
      getList(){
        categoryList().then(res => {
            if(res.data.length){
              this.items = []
              for(let i = 0;i<res.data.length;i++){
                this.items.push(res.data[i])
              }
            }else{
              this.items = []
            }
          }
        )
      },

      changeVal_guige_show(data){
        this.addnewguige[data.mp.target.dataset.iid].show = data.mp.detail
      },

      changeVal_guopinname(data){
        this.addnewguopin.text = data.mp.detail
        //查询数据库guopin最大id值

      },
      changeVal_guige_name(data){
        this.addnewguige[data.mp.target.dataset.iid].text = data.mp.detail

        this.addnewguige[data.mp.target.dataset.iid].id = data.mp.target.dataset.iid+1

      },

      changeVal_guige_kuncun(data){
        this.addnewguige[data.mp.target.dataset.iid].stock = data.mp.detail
      },




      onClose(e){
        let self = this
        if(e.mp.detail === 'confirm') {

          if(!self.addnewguopin.text){
            Notify({ type: 'danger', message: '请填写果品名' });
            setTimeout(function() {
              ;  self.$mp.page.selectComponent("#submitCaseDialog").stopLoading()
            },3000)
            return false
          }


          let nag = self.addnewguige.filter((obj,index) => {
            if(obj.text){
              return obj
            }
          })


          if(!nag.length){
            Notify({ type: 'danger', message: '至少写一个规格' });

            setTimeout(function() {
              ;  self.$mp.page.selectComponent("#submitCaseDialog").stopLoading()
            },3000)

            return false
          }
          let data = {
              text: self.addnewguopin.text,
              show: self.addnewguopin.show||false,
              children: nag
            }

          if(this.isEdit){

            data._id = this.items[this.mainActiveIndex]._id

            categoryEdit(data).then(res => {
              this.dialogAddNewFormShow=false
              this.getList()
            })
              .catch(err => {
              })

          }else{
            categoryAdd(data).then(res => {
              this.dialogAddNewFormShow=false
              this.getList()
            }).catch(err => {

              })
          }





          // if(!this.userVal_.username || !this.userVal_.password) {
          //   Notify({ type: 'danger', message: "请输入用户名密码"});
          //   setTimeout(function() {
          //     ;  self.$mp.page.selectComponent("#submitCaseDialog").stopLoading()
          //   },3000)
          // }else{
          //   this.getAdduser()
          // }
        } else if(e.mp.detail === 'cancel') {
          this.dialogAddNewFormShow=false
        }
      },

      addguige(){
        this.addnewguige.push({
          text:"",
          stock:"",
          show:true,
          id:this.addnewguige.length
        })

        console.log(this.addnewguige)

      },
      goAdd(){
        this.addnewguige=[{
          text:"",
          id:"",
          stock:"",
          show:true
        }]

         this.addnewguopin={
          text:"",
            id:"",
        }

        this.dialogAddNewFormShow = true

      },
      goEdit(){
        this.isEdit = true

        this.addnewguopin={
          text:this.items[this.mainActiveIndex].text,
          id:this.items[this.mainActiveIndex].id
        }

        this.addnewguige=this.items[this.mainActiveIndex].children
        this.dialogAddNewFormShow = true

      },
      goRefresh(){
        Toast.loading({
          message: '建设中...'
        });
      },
      goDel(){
        let t = this
        Dialog.confirm({
          message: '确定删除果品【'+t.items[t.mainActiveIndex].text+'】？'
        }).then(() => {
          wx.cloud.init({
            env: t.globalData.env
          })
          Toast.loading({
            message: '加载中...'
          });
          categoryDel({"_id":t.items[t.mainActiveIndex]._id}).then(res => {
            t.getList()
            Toast.success('删除成功！');
          })
        }).catch(() => {
          // on cancel
        });





      },


      onClickNav(event) {

        this.mainActiveIndex = event.mp.detail.index || 0
      },
       onClickItem(event) {


         this.activeId =  this.activeId === event.mp.detail.id ? null : event.mp.detail.id;
      }
    }

  }
</script>


<style>
  .btnm { padding: 30rpx}
  .van-button{ margin: 20rpx}

  .lidiv ._van-button{float: right;}
  .lidiv ._van-switch{float: right; margin-top: 20rpx; margin-right: 10px}

  .kucun{ float: right}
  ._van-button .van-button--danger{min-width:var(--button-mini-min-width,22px)}

</style>
